<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\Backend;
use hg\apidoc\annotation as Apidoc;
use think\facade\Db;

/**
 * 机构管理
 * @Apidoc\Group("base")
 * @package app\admin\controller
 */
class Org extends Backend
{
    /**
     * 初始化参数
     * @author 贾二小
     * @since 2021/7/3
     */
    public function initialize()
    {
        $this->config = [
            'name'=>'机构管理',
            'table_name'=>'org',//表名
            'table_alias' => 'a',//别名
            'table_field'=>'*',//显示默认字段
            'form_field' => 'id,pid,pids,name,code,sort,status,remark',//表单字段，没有设置则默认为显示字段默认是不能有*和.)
            'form_validated1' => [
                'name' => ['msg' => '机构名称不能为空', 'regex' => false, 'pcre' => '',],
                'code' => ['msg' => '机构编码不能为空', 'regex' => false, 'pcre' => '',],
            ],//表单验证
            'form_validated2' => ['name', 'code'],//重复验证
            'search_table'=> null,//关联表时，需要重写
            'is_limit'=> true,//是否分页显示
            'search_field' => 'id,pid,pids,name,code,sort,status,remark,create_user_id,create_date,update_user_id,update_date',//查询表格字段
            'search_param'=>[
                ['field' => 'name', 'type' => '=', 'param'=> 'name'],
            ],//查询表格条件
            'is_delete'=> true,//是否假删除
        ];
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表数据
     * @author 贾二小
     * @since 2021/7/2
     */
    public function page()
    {
        // 根据父机构id查询
        $pid = intval(input('pid'));
        if(!empty($pid)){
            $pids = input('pids');
            $this->config['search_table'] = Db::name($this->config['table_name'])
                ->alias($this->config['table_alias'])
                ->where('a.id','=',$pid)
                ->whereOr('a.pids','like',$pids.',['.$pid.']%');
        }
        parent::page(); // TODO: Change the autogenerated stub
    }

    /**
     * 组织架构树数据
     * @author 贾二小
     * @since 2021/7/2
     */
    public function tree(){
        $data = Db::name($this->config['table_name'])->field('id,pid,pids,name as title')->where(['is_delete'=>0])->order('sort')->select();
        $data = get_tree($data,0);
        $this->success($data);
    }

}